package com.kabao.demo;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;


public class SignInterceptor implements HandlerInterceptor {

    private Logger log = LoggerFactory.getLogger(SignInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从request请求体中拿到body中的JSON对象参数
        if(!(request instanceof RequestWrapper)){
            request = new RequestWrapper(request);
        }
        RequestWrapper wrapper = (RequestWrapper) request;
        String jsonBody = wrapper.getBodyString();
        System.out.println("jsonBody = " + jsonBody);
        return true;
    }

    // 生成签名（MD5(params+salt)截取8-24位）
//    private String generateSign(String params) throws Exception {
//        CabineFactoryConfig cabineFactoryConfig = (CabineFactoryConfig)SpringContextUtil.getBean("cabineFactoryConfig");
//        String salt = cabineFactoryConfig.getSalt();
//        String md5Txt = md5(params + salt);
//        return md5Txt.substring(8, 24);
//    }

    // MD5加密工具
    private String md5(String content) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(content.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}